package Thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

//生产者消费者模型
public class ThreadDemo17 {
    public static void main(String[] args) {
        //创建一个阻塞队列作为交易场所
        BlockingQueue<Integer> queue=new LinkedBlockingDeque<>();
        //消费者线程
        Thread customer=new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        int val=queue.take();
                        System.out.println("消费元素："+val);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        customer.start();
        //生产者线程
        Thread producer=new Thread(){
            @Override
            public void run() {
                for (int i = 0; i <10000 ; i++) {
                    try {
                        queue.put(i);
                        System.out.println("生产元素："+i);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        producer.start();
        try {
            producer.join();
            customer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
